package cn.yuan.org.service.impl;

import cn.yuan.basic.service.impl.BaseServiceImpl;
import cn.yuan.basic.util.MD5Utils;
import cn.yuan.basic.util.PageList;
import cn.yuan.basic.util.StrUtils;
import cn.yuan.org.domain.Employee;
import cn.yuan.org.mapper.EmployeeMapper;
import cn.yuan.org.query.EmployeeQuery;
import cn.yuan.org.service.IEmployeeService;
import cn.yuan.user.domain.Logininfo;
import cn.yuan.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService{
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;


    /*批量删除*/
    @Override
    @Transactional
    public void batchDel(Long[] ids) {
        employeeMapper.batchDel(ids);
    }

    /**
     * 需要及联操作登录信息表
     * @param employee
     */
    @Override
    public void save(Employee employee){
        initEmployee(employee);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo info = new Logininfo();
        BeanUtils.copyProperties(employee,info);
        info.setType(0); //0 是员工 1 用户
        return info;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5 = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5);
    }

    @Override
    public void update(Employee employee) {
        initEmployee(employee);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
        super.update(employee);
    }

    @Override
    @Transactional
    public void remove(Long id){
        // 通过员工id查询员工 从而获取到loginInfoId
       Employee employee =  employeeMapper.loadById(id);
       if(employee!=null){
           // 删除loginInfo
           logininfoMapper.remove(employee.getLogininfo_id());
           // 删除employee
           employeeMapper.remove(id);
       }
    }
}
